//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj注册

#import "RegisterViewController.h"
#import "LanguageController.h"
#import "CountryCodeVC.h"
#import "AllCountryCodeVC.h"
#import "NBPhoneNumberUtil.h"
#import "CaptchaView.h"
#import "EnterCodeController.h"
#import "RegisterEmailVC.h"

@interface RegisterViewController ()
@property (weak, nonatomic) IBOutlet UILabel *countryCodeLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet MJUITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet MJUIBaseButton *confirmButton;
@property (weak, nonatomic) IBOutlet UIView *phoneNumberBgView;
@property (weak, nonatomic) IBOutlet UILabel *loginLabel;
@property (nonatomic, assign) BOOL isRegister;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

}

- (void)mj_setUI{
    [super mj_setUI];
    
    [self.navigationController setNavigationBarHidden:true animated:NO];

//    NSDictionary *data = @{@"userId":@"23423423423"};
//    [UserManager.shared saveUserInfo:data];
    

    self.phoneNumberTextField.mj_disableThirdPartyKeyboard = true;
    self.phoneNumberTextField.font = MJUIFontMake(20);
    
    self.tipLabel.hidden = true;
    self.countryCodeLabel.text = @"";
    [self.phoneNumberTextField mj_setClearButtonWithImage:[UIImage imageNamed:@"icon_del"]];

    NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
    
    if(!self.countryAreaCode){
        self.countryAreaCode = [HealthHelper getCountryAreaCode];
    }
    
    NSString *code = [NSString stringWithFormat:@"+%@",self.countryAreaCode[@"区号"]];
    self.countryCodeLabel.text = code;
    if([self.countryCodeLabel.text containsString:@"+86"]){
        self.phoneNumberTextField.mj_limitedNumber = 11;
    }
    MJWeakSelf
    RAC(self.confirmButton, mj_enabled) = [RACSignal combineLatest:@[self.phoneNumberTextField.rac_textSignal] reduce:^id _Nullable(NSString * text){

        BOOL enable = false;
        if([self.countryCodeLabel.text containsString:@"+86"]){
            if(text.length == 11 && [text mj_isMobileNumber]){
                enable = true;
            }else{
                enable = false;
            }
        }else{
            NBPhoneNumber *myNumber = [phoneUtil parse:text
                                          defaultRegion:weakSelf.countryAreaCode[@"ISO"] error:nil];
            enable = [phoneUtil isValidNumber:myNumber];
            NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber] ? @"YES":@"NO");
        }
      
        if(enable){
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_appColor width:2];
        }else{
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.clearColor width:2];
            weakSelf.tipLabel.hidden = true;
        }
        return @(enable);
    }];
    

    
    NSLocale *locale = [NSLocale currentLocale];
    // 获取国家代码
    NSString *countryCode = [locale objectForKey:NSLocaleCountryCode];
    // 获取国家名
    NSString *displayName = [locale displayNameForKey:NSLocaleCountryCode value:countryCode];
    NSLog(@"Country Code: %@", countryCode);
    NSLog(@"Country Name: %@", displayName);
    
    [self.phoneNumberTextField mj_becomeFirstResponder];
    
    self.phoneNumberTextField.text = self.phoneNumber;

}

#pragma mark - 方法
- (void)requestData{
    
}

- (IBAction)handleLanguageButtonClick:(UIButton *)sender {
    LanguageController *vc = [[LanguageController alloc]init];
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleEmailRegisterButtonClick:(UIButton *)sender {
   
    if([self.navigationController mj_containTargetVCWithClass:RegisterEmailVC.class]){
        [self mj_popViewController];
    }else{
        RegisterEmailVC *vc = [[RegisterEmailVC alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
}

- (IBAction)handleRegisterButtonClick:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:true];
}

- (IBAction)handleCountryCodeButtonClick:(UIButton *)sender {
    
    MJWeakSelf
    AllCountryCodeVC *vc = [[AllCountryCodeVC alloc]init];
    vc.handleCountryCodeBlock = ^(NSDictionary *countryAreaCode) {
        NSString *code = [NSString stringWithFormat:@"+%@",countryAreaCode[@"区号"]];
        weakSelf.countryCodeLabel.text = code;
        weakSelf.countryAreaCode = countryAreaCode;

    };
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleConfirmButtonClick:(UIButton *)sender {
    [self.phoneNumberTextField resignFirstResponder];

    //判断手机号码是否注册
    NSDictionary *params =  @{
        @"countryCode": self.countryAreaCode[@"区号"],
        @"phoneNumber": self.phoneNumberTextField.text,
        @"region": self.countryAreaCode[@"ISO"],
    };
    MJWeakSelf
    [MJHttpNetWorking requestWithParams:params requestUri:user_findByPhone requestType:RequestTypeGet showLoading:true success:^(MJBaseModel *model) {
        
        if(model.code == 200){
            if(model.data){
                weakSelf.isRegister = true;
            }else{
                weakSelf.isRegister = false;
            }
            
            MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
            configure.confirmButtonColor = UIColor.mj_appColor;
            configure.confirmTitle = MJUILocalizedString(@"OK_qd");
            configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
            configure.messageAlignmentCenter = true;
            NSString *phone = [NSString stringWithFormat:@"+%@%@",self.countryAreaCode[@"区号"],self.phoneNumberTextField.text];
            NSString *messageString = [[MJUILocalizedString(@"We will send a verification code to the following number:") stringByAppendingString:@"\n"] stringByAppendingString:phone];
            [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Mobile Number Confirmation") message:messageString configure:configure confirmBlock:^{
                
                [weakSelf sendAnjCcaptchaCode];

            } cancelBlock:^{

            }];
        }

    } failure:^(NSError *error) {

    }];
    
    
    
    
}

/// 滑块验证码
- (void)sendAnjCcaptchaCode {
    
    MJWeakSelf
    [CaptchaView showWithType: puzzle CompleteBlock:^(NSString *  result) {
        NSLog(@"result=======================%@",result);
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
            @"countryCode": self.countryAreaCode[@"区号"],
            @"phoneNumber": self.phoneNumberTextField.text,
            @"region": self.countryAreaCode[@"ISO"],
            @"code": result,
        }];
        [MJHttpNetWorking requestWithParams:parms requestUri:captcha_sendSms requestType:RequestTypePost showLoading:true success:^(MJBaseModel *model) {
            
            if (model.code ==  200){
                EnterCodeController *vc = [[EnterCodeController alloc]init];
                vc.captchaCodeType = weakSelf.isRegister ? CaptchaCodeTypeLogin : CaptchaCodeTypeRegister;
                vc.phone = weakSelf.phoneNumberTextField.text;
                vc.countryAreaCode = weakSelf.countryAreaCode;
                [weakSelf.navigationController pushViewController:vc animated:true];
            }else if(model.code ==  412){
                [RoyHud showToast:MJUILocalizedString(@"Too frequent, Retry later.")];
            }
            
        } failure:^(NSError *error) {
            
        }];
        
        

    }];

    
    
    
}
- (void)xxx{
    MJWeakSelf
    [MJHttpNetWorking requestWithParams:@{@"appName":@"uricacid",@"deviceType":@"iOS"} requestUri:GetAppUpgrade requestType:RequestTypeGet showLoading:true success:^(MJBaseModel *model) {
        
        if(model.code == 200){
            weakSelf.tipLabel.hidden = false;
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_redColor width:2];
        }

    } failure:^(NSError *error) {
        
    }];
}
#pragma mark - 代理

#pragma mark - 懒加载

@end
